<template>
  <div class="article-list" ref="list" @scroll="onScroll">
    <van-pull-refresh v-model="pullLoading" @refresh="onRefresh">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <van-cell
          v-for="item in list"
          :key="item.art_id"
          :to="`/article/${item.art_id}`"
        >
          <!-- 标题 -->
          <div class="title">{{ item.title }}</div>
          <!-- 图片 -->
          <van-grid :border="false" :column-num="item.cover.type">
            <van-grid-item
              v-for="(pic, index) in item.cover.images"
              :key="index"
            >
              <van-image class="pic" :src="pic" />
            </van-grid-item>
          </van-grid>
          <!-- 讯息 -->
          <div class="info-box">
            <span>{{ item.aut_name }}</span>
            <span>{{ item.comm_count }}</span>
            <span>{{ item.pubdate | relvTime }}</span>
            <van-icon style="float: right" name="cross" />
          </div>
        </van-cell>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { articleListAPI } from '@/api/news'
export default {
  props: {
    channel_id: {
      type: Number,
      required: true
    }
  },
  data () {
    return {
      list: [],
      loading: false,
      finished: false,
      timestamp: Date.now(),
      pullLoading: false,
      scrollTop: 0
    }
  },
  activated () {
    this.$refs.list.scrollTop = this.scrollTop
  },
  methods: {
    onScroll () {
      this.scrollTop = this.$refs.list.scrollTop
    },
    async onLoad () {
      // 异步更新数据
      const res = await articleListAPI({
        channel_id: this.channel_id,
        timestamp: this.timestamp
      })
      this.timestamp = res.data.pre_timestamp
      //   console.log(res)
      this.list.push(...res.data.results)
      this.loading = false
      this.finished = this.timestamp === null
    },
    // 下拉刷新
    async onRefresh () {
      const res = await articleListAPI({
        channel_id: this.channel_id,
        timestamp: Date.now()
      })
      this.timestamp = res.data.pre_timestamp
      this.list = res.data.results
      this.pullLoading = false
      this.finished = false
    }
  }
}
</script>

<style lang="less" scoped>
.article-list {
  position: fixed;
  top: 90px;
  bottom: 50px;
  overflow: auto;
  width: 100vw;
}
.pic {
  height: 120px;
}

.info-box {
  span {
    color: gray;
    &:nth-child(2) {
      margin: 0 15px;
    }
  }
}
</style>
